package com.imooc.bilibili.service;

import com.alibaba.fastjson.JSONArray;
import com.imooc.bilibili.dao.UserFollowingDao;
import com.imooc.bilibili.domain.FollowingGroup;
import com.imooc.bilibili.domain.User;
import com.imooc.bilibili.domain.UserFollowing;
import com.imooc.bilibili.domain.UserInfo;
import com.imooc.bilibili.constant.UserConstant;
import com.imooc.bilibili.exception.ConditionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class UserFollowingService {

    @Autowired
    private UserService userService;

    @Autowired
    private UserFollowingDao userFollowingDao;

    @Autowired
    private FollowingGroupService followingGroupService;

    /**
     * 添加用户关注
     * @param userFollowing
     * @return
     */
    // @Transactional(propagation = Propagation.REQUIRED,
    //                rollbackFor = {Exception.class,RuntimeException.class})
    @Transactional
    public void addUserFollowing(UserFollowing userFollowing) {
        Integer groupId = userFollowing.getGroupId();
        if (groupId == null) {
            FollowingGroup followingGroup = followingGroupService.getByType(UserConstant.USER_FOLLOWING_GROUP_TYPE_DEFAULT);
            userFollowing.setGroupId(Math.toIntExact(followingGroup.getId()));
        }else{
            FollowingGroup followingGroup = followingGroupService.getById(groupId);
            if (followingGroup == null) {
                throw new ConditionException("关注的分组不存在！");
            }
        }
        Integer followingId = userFollowing.getFollowingId();
        Long followingId2 = Long.valueOf(followingId);
        User user = userService.getUserById(followingId2);
            if (user == null) {
                throw new ConditionException("关注的用户不存在！");
            }


        // 先删除再关注（懒得写更新）
        userFollowingDao.deleteUserFollowing(userFollowing.getUserId(),followingId);
        userFollowing.setCreateTime(new Date());
        userFollowingDao.addUserFollowing(userFollowing);
    }

    /**
     * 获取用户关注列表
     * @param userId
     * @return
     */
    public List<FollowingGroup> getUserFollowings(Long userId) {
        // 获取用户关注列表
        List<UserFollowing> userFollowingList = userFollowingDao.getUserFollowings(userId);
        Set<Integer> followingIdSet = userFollowingList.stream().map(UserFollowing::getFollowingId).collect(Collectors.toSet());
        // 查询关注的用户信息
        List<UserInfo> userInfoList = null;
        if (followingIdSet .size() > 0) {
             userInfoList = userService.getUserInfoByUserIds(followingIdSet);
        }
        // 将关注的用户信息与关注表中每条记录一一对应
        for (UserFollowing userFollowing : userFollowingList){
           for(UserInfo userInfo : userInfoList){
               Integer followingId = userFollowing.getFollowingId();
               Long followingIdL = Long.valueOf(followingId);
               Long userInfoUserId = userInfo.getUserId();
               if(followingIdL.equals(userInfoUserId)){
                   userFollowing.setUserInfo(userInfo);
               }
           }
       }
        System.out.println(userFollowingList);
        // 最后通过分组id 完成不同分组下关注列表的收集
        List<FollowingGroup> followingGroupList = followingGroupService.getByUserId(userId);
        FollowingGroup allGroup = new FollowingGroup();
        allGroup.setName(UserConstant.USER_FOLLOWING_GROUP_ALL_NAME);
        allGroup.setUserInfos(userInfoList);
        List<FollowingGroup> rest = new ArrayList<>();
        rest.add(allGroup);

        for (FollowingGroup followingGroup : followingGroupList){
            List<UserInfo> infoList = new ArrayList<>();
            for (UserFollowing userFollowing : userFollowingList){
                Long id = followingGroup.getId();
                Integer groupId = userFollowing.getGroupId();
                Long groupIdL = Long.valueOf(groupId);
                if(id.equals(groupIdL)){
                    infoList.add(userFollowing.getUserInfo());
                }
            }
            followingGroup.setUserInfos(infoList);
            rest.add(followingGroup);
        }
        return rest;
    }

    /**
     * 获取用户粉丝列表
     * @param userId
     * @return
     */
    @Transactional
    public List<UserFollowing> getUserFans(Long userId) {
        // 获取粉丝列表
        List<UserFollowing> fanList = userFollowingDao.getUserFans(userId);
        // 获取粉丝的userId
        Set<Long> fanIdSetL = fanList.stream().map(UserFollowing::getUserId).collect(Collectors.toSet());
        List<Integer> integer = JSONArray.parseArray(fanIdSetL.toString(), Integer.class);
        Set<Integer> fanIdSet = integer.stream().collect(Collectors.toSet());
        List<UserInfo> userInfoList = null;
        if (fanIdSet.size() > 0){
            // 获取粉丝的详细信息
            userInfoList = userService.getUserInfoByUserIds(fanIdSet);
        }
        // 获取我的关注列表
        List<UserFollowing> userFollowingList = userFollowingDao.getUserFollowings(userId);
        for (UserFollowing fan : fanList){
            for (UserInfo userInfo : userInfoList){
                if(fan.getUserId().equals(userInfo.getUserId())){
                    userInfo.setFollowed(false);
                    fan.setUserInfo(userInfo);
                }
            }
            for (UserFollowing userFollowing : userFollowingList){
                if (fan.getUserId().equals(Long.valueOf(userFollowing.getFollowingId()))){
                    fan.getUserInfo().setFollowed(true);
                }
            }
        }

        return fanList;
    }

    /**
     * 新增用户关注分组
     * @param followingGroup
     * @return
     */
    public Long addUserFollowingGroups(FollowingGroup followingGroup) {
        followingGroup.setCreateTime(new Date());
        followingGroup.setType(UserConstant.USER_FOLLOWING_GROUP_TYPE_USER);
        followingGroupService.addFollowingGroup(followingGroup);
        Long groupId = followingGroup.getId();
        return groupId;
    }

    /**
     * 获取用户关注分组
     * @param
     * @return
     */
    public List<FollowingGroup> getUserFollowingGroups(Long userId) {
        return followingGroupService.getUserFollowingGroups(userId);
    }

    /**
     * 检查列表中用户是否被关注过
     * @param userInfoList
     * @return
     */
    public List<UserInfo> checkFollowingStatus(List<UserInfo> userInfoList,Long userId) {
        List<UserFollowing> userFollowings = userFollowingDao.getUserFollowings(userId);
        for (UserInfo userInfo : userInfoList){
            userInfo.setFollowed(false);
            for (UserFollowing userFollowing : userFollowings){
                if (Long.valueOf(userFollowing.getFollowingId()).equals(userInfo.getUserId())){
                    userInfo.setFollowed(true);
                }
            }
        }
        return userInfoList;
    }
}
